<?php

namespace plugin\webman\gateway;

use Exception;
use GatewayWorker\Lib\Gateway;
use ModbusTcpClient\Composer\Read\ReadRegistersBuilder;
use ModbusTcpClient\Network\BinaryStreamConnection;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersRequest;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersResponse;
use ModbusTcpClient\Packet\ResponseFactory;
use support\Redis;

class Events
{
    public static function onWorkerStart($worker)
    {

    }

    public static function onConnect($client_id)
    {

    }

    public static function onWebSocketConnect($client_id, $data)
    {

    }

    public static function onMessage($client_id, $message)
    {
        //tcp服务,接受modbus-tcp的数据
        //转换为16进制
        $hex = bin2hex($message);
        $length = strlen($hex);
        $hex = strtoupper($hex);
        //寄存器的值
        $register_value = hexdec(substr($hex,-4,4));
        if ($length <= 24){
            $string = substr($hex,0,20);
            $register_address = hexdec(substr($hex,-8,4));
            //获取寄存器的值
            $value = Redis::get("modbus".$register_address);
            if (empty($value)){
                Redis::set("modbus".$register_address,$register_value);
            }
            //获取值
            $string1 = substr($hex,0,16);
            $new_string = $string1."02".sprintf("%04d", dechex($value));
            //var_dump($hex,$string,$new_string);
            $send_string = str_replace("$",'',pack("H*",$new_string));
            var_dump($send_string,$message);
            Gateway::sendToClient($client_id,$message);
        }else{
            $string = substr($hex,0,22);
            //寄存器的地址
            $register_address = hexdec(substr($hex,-10,4));
            //把值存入寄存器
            Redis::set("modbus".$register_address,$register_value);
            //Gateway::sendToClient($client_id,$string);
            Gateway::sendToClient($client_id,$message);
        }

        //Gateway::sendToClient($client_id,$send_string);
        //Gateway::sendToClient($client_id, "receive message $message");

    }

    public static function onClose($client_id)
    {

    }

}
